<template>
    <div class="px-8">
        <com-filterTable
            :ref="pageConfig.key"
            class=""
            :services="pageConfig.serviceHandle"
            :filter-form-config="pageConfig.formConfig"
            :filterInline="false"
            :params="{}"
            :filterCol="4"
            filterLabelWidth="90px"
            :table-border="true"
            :showFormFilter="true"
            :showRequestNum="false"
            :top-operation="pageConfig.topOperation"
            :table-column="pageConfig.columnConfig"
            :queryDataHandle="queryDataHandle"
            :dataFormatHandle="dataFormatHandle"
            :autoLoad="true"
        />
        <com-formDialog
            ref="dialog"
            v-bind="dialogData"
            @changeOut="changeOut"
            @cancel="dialogCancelHandle"
            @submit="submitHandle"
        />
    </div>
</template>

<script>
import { selectUserList, registerUser, updateUser, deleteUser, resetPassWord } from "@/service/api.js";
import _ from "lodash";
//   import {dateTimeFormat} from "@/utils/time.js"
import moment from "moment";
import { formFieldDoctor } from "@/utils/formFieldDoctor.js";
export default {
    name: "userManage",
    data() {
        return {
            activeName: "filterTable",
            oldFormData: null,
            newPassword: '',
            comDialogData: {},
            batchSelected: [],
            pageConfig: {
                key: "filterTable",
                serviceHandle: (data) => {
                    return selectUserList(data);
                },
                params: {},
                formConfig: [
                    { key: "id", label: "用户编号" },
                    { key: "userName", label: "用户名称" },
                ],
                columnConfig: [
                    { type: "select" },
                    { value: "userName", label: "用户名" },
                    { value: "realName", label: "姓名" },
                    {
                        value: "gender",
                        label: "性别",
                        formatter: (row) => {
                            return row.gender ? "男" : "女";
                        },
                    },
                    { value: "phone", label: "联系电话" },
                    { value: "departmentId", label: "所属科室" },
                    { value: "roleId", label: "角色" },
                    { value: "title", label: "职称" },
                    {
                        value: "createTime",
                        label: "创建时间",
                        width: 180,
                        formatter: (row) => {
                            return moment(row.createTime).format(
                                "YYYY-MM-DD HH:mm:ss"
                            );
                        },
                    },
                    {
                        value: "action",
                        type: "render",
                        width: 200,
                        label: "操作",
                        render: (h, { data: { row } }) => {
                            const onCancelHandle = (flag) => {
                                this.dialogCancelHandle();
                                if (flag) {
                                    row.isRecord = true;
                                }
                            };
                            const recordHandle = () => {
                                this.comDialogData = {
                                    submitHandle: (data) => {
                                        return new Promise((resolve) => {
                                            setTimeout(resolve(true), 1000);
                                        });
                                    },
                                    configs: [
                                        {
                                            key: "record",
                                            label: "",
                                            noLabel: true,
                                            fullLine: true,
                                            type: "render",
                                            render: (h) => {
                                                // return <recorder currentLink={this.currentLink} activeRow={row} cancelHandle={onCancelHandle}></recorder>
                                            },
                                        },
                                    ],
                                    activeRow: row,
                                    title: "录音",
                                    width: "750px",
                                    height: "400px",
                                    labelPosition: "left",
                                    labelWidth: "90px",
                                    col: 1,
                                    slotRenders: {
                                        footer: (h) => {
                                            return <div></div>;
                                        },
                                    },
                                };
                                this.$refs.dialog.show();
                            };
                            const editBtn = (
                                <el-button type="text" on-click={() => this.addOrEditHandle(row)}>修改</el-button>
                            );
                            const delBtn = (
                                <el-button type="text" on-click={() => this.deleteList([row])}>删除</el-button>
                            );
                            const detailBtn = (
                                <el-button type="text" on-click={() => this.resetPassword(row)}>重置密码</el-button>
                            );

                            return [editBtn, delBtn, detailBtn];
                        },
                    },
                ],
                topOperation: {
                    left: [
                        {
                            name: "新增",
                            key: "add",
                            type: "primary",
                            requireArguments: ["batchSelected", "filterForm"], // 表格选中数据，查询表单数据
                            handle: (batchSelected) => {
                                this.addOrEditHandle();
                            },
                        },
                        // {
                        //     name: '删除',
                        //     key: 'delete',
                        //     requireArguments: ["batchSelected", "filterForm"], // 表格选中数据，查询表单数据
                        //     handle: (batchSelected) => {
                        //         console.log(batchSelected);
                        //         if(!batchSelected||!batchSelected.length) {
                        //             this.$message.error('请选择要删除的数据！')
                        //             return;
                        //         }
                        //         this.deleteList(batchSelected)
                        //     },
                        // }
                    ],
                },
            },
        };
    },
    watch: {},
    computed: {
        dialogData() {
            let { comDialogData } = this;
            return {
                configs:
                    this[comDialogData.configName] || comDialogData.configs,
                ...comDialogData,
            };
        },
        formDialogConfig() {
            return [];
        },
    },
    mounted() {},
    methods: {
        changeOut({ key, formData } = {}) {
            this.oldFormData = { ...formData };
        },
        dataFormatHandle(data) {
            return {
                list: data.data,
                total: data.total,
            };
        },
        queryDataHandle(params) {
            let temp = {
                ...params,
            };
            return temp;
        },
        loadList() {
            let ref = this.$refs[this.activeName];
            if (Array.isArray(ref)) {
                ref = ref[0];
            }

            ref.filterFormQueryHandle();
        },
        dialogCancelHandle() {
            this.$refs.dialog.close();
        },
        async submitHandle(data) {
            let handle = this.dialogData.submitHandle;
            handle = typeof handle !== "function" ? this[handle] : handle;
            if (handle) {
                let loading = await this.$store.dispatch("global/loading");
                handle(data)
                    .then((res) => {
                        console.log(res, 'res');
                        loading.close();
                        this.$refs.dialog.close();
                        this.loadList();
                    })
                    .catch((e) => {
                        console.log(e);
                        loading.close();
                    });
            }
        },
        // 新增或编辑
        addOrEditHandle(row) {
            this.comDialogData = {
                submitHandle: (data) => {
                    let handle = registerUser;
                    let params = {
                        ...data,
                    }
                    if(row) {
                        handle = updateUser;
                        params.id = row.id;
                    }else {
                        params.password = '123456'; // 给个默认密码
                    }
                    return handle(params)
                },
                initFormData: row,
                configs: [
                    { key: "userName", label: "用户名", required: true, },
                    { key: "realName", label: "姓名", required: true, },
                    { key: "gender", label: "性别", required: true, type: "select", options: [{ label: "男", value: true }, { label: "女", value: false }], },
                    { key: "phone", label: "联系电话", required: true, },
                    { key: "email", label: "邮箱" },
                    { key: "title", label: "职称" },
                    formFieldDoctor.depart.call(this, "所属科室", "departmentId", {
                        required: true
                    }),
                    formFieldDoctor.role.call(this, "所属角色", "roleId", {
                        required: true
                    }),
                    formFieldDoctor.status.call(this, "状态", "status", {
                        required: true
                    }),

                ],
                activeRow: row,
                title: row?"修改":"新增",
                width: "750px",
                height: "300px",
                labelPosition: "left",
                labelWidth: "110px",
                col: 2,
            };
            this.$refs.dialog.show();
        },
        // 重置密码
        resetPassword(row) {
            this.comDialogData = {
                submitHandle: (data) => {
                    let handle = resetPassWord;
                    let params = {
                        ...data,
                    }
                    
                    return handle(params)
                },
                configs: [

                    formFieldDoctor.password.call(this, "原密码", "oldPassword", {
                        required: true
                    }),
                    formFieldDoctor.password.call(this, "新密码", "newPassword", {
                        required: true,
                        changeToEmit: true,
                    }),
                    formFieldDoctor.password.call(this, "确认新密码", "newPassword1", {
                        required: true,
                        rules: [
                            {
                                validator: (rule, value, callback) => {
                                    if (value !== this.oldFormData.newPassword) {
                                        callback(new Error("两次密码不一致"));
                                    } else {
                                        callback();
                                    }
                                },
                                trigger: "blur"
                            }
                        ]
                    }),

                ],
                activeRow: row,
                title: "重置密码",
                width: "550px",
                height: "300px",
                labelPosition: "left",
                labelWidth: "120px",
                col: 1,
            };
            this.$refs.dialog.show();
        },
        // list删除
        deleteList(list) {

            let params = {
                id: list.map(item => item.id).join(',')
            }
            this.$confirm("确定要删除吗？").then(() => {
                this.comDialogData = {
                    submitHandle: () => {
                        return deleteUser(params)
                    }
                }
                this.submitHandle();
            });
        },

    },
};
</script>
